package test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.HashMap;

public class demo10UdpEchoServer {
    DatagramSocket socket = null;
    public demo10UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器已启动");
        while (true){
            //接收客户端请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            //计算响应
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            String respond = process(request);
            //将响应发送回客户端
            DatagramPacket respondPacket = new DatagramPacket(respond.getBytes(),
                    respond.length(), requestPacket.getSocketAddress());
            socket.send(respondPacket);
            System.out.printf("[%s:%d] req=%s resp=%s\n" ,requestPacket.getSocketAddress(),
                            requestPacket.getPort(), request, respond);
        }
    }

    private String process(String request) {
        HashMap<String, String> dic = new HashMap<>();
        dic.put("cat", "小猫");
        dic.put("dog", "小狗");
        String means = dic.get(request);
        return means;
    }

    public static void main(String[] args) throws IOException {
        demo10UdpEchoServer demo10UdpEchoServer = new demo10UdpEchoServer(9090);
        demo10UdpEchoServer.start();
    }
}
